package com.shijunhao.graduation.utils;

import com.shijunhao.graduation.domain.entity.OrgUser;
import com.shijunhao.graduation.domain.entity.SystemLoginLog;
import com.shijunhao.graduation.service.business.IBusinessUserInfoService;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @author: shijunhao
 * @date: 2022/3/16 16:53
 * @description:
 */
@Component
public class SystemLoginLogUtils {

    private final IBusinessUserInfoService businessUserInfoService;

    @Autowired
    public SystemLoginLogUtils(IBusinessUserInfoService businessUserInfoService) {
        this.businessUserInfoService = businessUserInfoService;
    }

    public SystemLoginLog getLoginLog(String msg){
        SystemLoginLog log = new SystemLoginLog();
        OrgUser user = businessUserInfoService.getCurrentUser();
        if (Objects.nonNull(user)) {
            log.setId(user.getId());
            log.setUsername(user.getUsername());
        }
        HttpServletRequest request = ServletUtils.getRequest();
        log.setIp(ServletUtils.getClientIP(request));
        String userAgentString = request.getHeader("User-Agent");
        UserAgent userAgent = UserAgent.parseUserAgentString(userAgentString);
        log.setBrowser(userAgent.getBrowser().getName());
        log.setOs(userAgent.getOperatingSystem().getName());
        log.setDescription(msg);
        return log;
    }
}
